package com.bankscene.screenfit.model;

import com.bankscene.screenfit.dict.ErrorDict;
import com.bankscene.screenfit.exception.ModelModeException;

import rx.functions.Func1;

import static com.bankscene.screenfit.dict.CommDict.HTTP_REQ_FLAG_SUCCESS;

/**
 * 一个包装类，将结果包装了起来，但是在使用的时候要给出一个明确的类型:
 * Observable<HttpResult<User>>
 * Observable<HttpResult<List<Subject>>>
 * @param <T>
 */
public class HttpResult<T> {

    private int resultCode;
    private String resultMessage;

    private T data;

    public int getResultCode() {
        return resultCode;
    }

    public void setResultCode(int resultCode) {
        this.resultCode = resultCode;
    }

    public String getResultMessage() {
        return resultMessage;
    }

    public void setResultMessage(String resultMessage) {
        this.resultMessage = resultMessage;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "HttpResult{" +
                "resultCode=" + resultCode +
                ", resultMessage='" + resultMessage + '\'' +
                ", data=" + data +
                '}';
    }

    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T>   Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    public class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {

        @Override
        public T call(HttpResult<T> httpResult) {
            if (httpResult.getResultCode() == Integer.parseInt(HTTP_REQ_FLAG_SUCCESS.toString())) {
                throw new ModelModeException(ErrorDict.ERROR_RES_NOTISNULL);
            }
            return httpResult.getData();
        }
    }
}
